#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<cstring>

int main(int argc, char* argv[])
{
	if(argc!= 3)
	{
		std::cout<<"Usage: "<<argv[0]<<" <server_ip> <server_port>"<<std::endl;
		return 1;
	}
	std::string server_ip = argv[1];
	int server_port = std::atoi(argv[2]);

	int sockfd = ::socket(AF_INET,SOCK_STREAM,0);
	if(sockfd < 0)
	{
		std::cout << "Create socket failed" << std::endl;
		return 2;
	}

	// client不需要显式的bind,也不需要监听,tcp是面向连接的，connect 底层会自动进行bind

	struct sockaddr_in server_addr;
	memset(&server_addr,0,sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = ::htons(server_port);
	server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());

	//  int connect(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
	int n = ::connect(sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr));
	if(n < 0)
	{
		std::cout << "connect fail" << std::endl;
	}

	// 通信
	std::string message;
	while(1)
	{
		std::cout << "ipput message: " ;
		std::getline(std::cin,message);

		char inbuffer[1024];
		n = write(sockfd,message.c_str(),message.size());
		if(n > 0)
		{
			int m = ::read(sockfd,inbuffer,sizeof(inbuffer));
			if(m > 0)
			{
				inbuffer[m] = 0;
				std::cout << inbuffer << std::endl;
			}
			else 
				break;
		}
		else 
			break;

	}

	::close(sockfd);

	return 0;
}